<?php

/**
 * Aihexpenses Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Croogo
 * @version  1.0
 * @author   Tran Van Dung <dungtv@ic-t.info>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class AihexpensesController extends AppController {

    /**
     * Controller name
     *
     * @var string
     * @access public
     */
    public $name = 'Aihexpenses';
    /**
     * Models used by the Controller
     *
     * @var array
     * @access public
     */
    public $uses = array('Aihexpense', 'Accountresume', 'Paymentschedule', 'Aihcontact', 'Bmatch', 'Currency');
    /**
     * Helpers used by the Controller
     *
     * @var array
     * @access public
     */
    public $helpers = array('Text', 'Html', 'Js');
    protected $paginate = array(
        'limit' => 10,
    );

    /**
     * Before executing controller actions
     *
     * @return void
     * @access public
     */
    public function beforeFilter() {
        parent::beforeFilter();
        
        if ($this->action == 'add' || $this->action == 'edit' || $this->action == 'admin_add' || $this->action == 'admin_edit') {
            $this->Security->validatePost = false;
        }
    }

    /**
     * Admin index
     *
     * @return void
     * @access public
     */
    public function admin_index() {
        $this->set('title_for_layout', __('AIH EXPENSE LIST'));
        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);
        
        $this->Aihexpense->recursive = 0;
        $this->paginate['Aihexpense']['order'] = 'Aihexpense.date ASC';

        $this->set('aihexpenses', $this->paginate());
    }
    
    public function admin_search() {
        $this->set('title_for_layout', __('AIH EXPENSE SEARCH'));
        
        $scriptSearchBox = $this->scriptSearchBox();
        $this->set('scriptSearchBox', $scriptSearchBox);
        $q = $this->params['named']['q'];
        $this->set('q', $q);
        
        $this->Aihexpense->recursive = 0;
        
        if($q == 'all'){
            
        }else{
            
            $this->paginate['Aihexpense']['conditions'] = array('OR' => array(
                                                            'Aihexpense.from LIKE' => '%'.$q.'%',
                                                            'Aihexpense.to LIKE' => '%'.$q.'%',
                                                            ));
        }
        $this->paginate['Aihexpense']['order'] = 'Aihexpense.date ASC';

        $this->set('aihexpenses', $this->paginate());
    }

    /**
     * Admin add
     *
     * @return void
     * @access public
     */
    public function admin_add() {
        $this->set('title_for_layout', __('AIH EXPENSE DETAIL'));

        $script = $this->datePicker();
        $this->set('script', $script);
        
        $script = $this->getJSONdata();
        $this->set('getJSON', $script);

        if (!empty($this->request->data)) {
            $this->request->data['Aihexpense']['amount'] = $this->request->data['Aihexpense']['amount'];
            $to_info = explode(PHP_EOL, $this->request->data['Aihexpense']['to']);
            $this->request->data['Aihexpense']['bank_code'] = trim(str_replace('Bank Code:', '', $to_info[1]));
            $this->request->data['Aihexpense']['branch_code'] = trim(str_replace('Branch Code:', '', $to_info[2]));
            $this->request->data['Aihexpense']['swift_code'] = trim(str_replace('SWIFT:', '', $to_info[4]));
            $this->request->data['Aihexpense']['date'] = date('Y-m-d', strtotime($this->request->data['Aihexpense']['date']));
            $refid_edit = $this->Accountresume->find('first', array('fields' => array('Accountresume.refid_edit'), 'conditions' => array('Accountresume.refid' => $this->request->data['Accountresume']['Accountresume'],)));
            $this->request->data['Aihexpense']['charge_payer'] = $this->request->data['Aihcontact']['Aihcontact'];
            $this->request->data['Aihexpense']['currency_id'] = $this->request->data['Currency']['Currency'];
            $currency = $this->Currency->find('first', array(
                'conditions' => array('Currency.id' => $this->request->data['Currency']['Currency'])));
            $this->request->data['Aihexpense']['currency'] = $currency['Currency']['name'];
            if(isset($this->request->data['AccResumeRelated'])){
                $this->request->data['Aihexpense']['refid'] = $this->request->data['Accountresume']['Accountresume'];
                $this->request->data['Aihexpense']['refid_edit'] = $refid_edit['Accountresume']['refid_edit'];
                $this->request->data['Aihexpense']['acc_resume_related'] = $this->request->data['AccResumeRelated'];
                $this->request->data['Aihexpense']['paydetailid'] = $this->request->data['Paymentschedule']['Paymentschedule'];
            }else{
                $this->request->data['Aihexpense']['acc_resume_related'] = 0;
                $this->request->data['Aihexpense']['refid_edit'] = "Not related with acc resume";
                $this->request->data['Aihexpense']['paydetailid'] = "Not related with Payment detail";
                $this->request->data['Aihexpense']['refid'] = "Not related with acc resume";
            }
            //php_debug($this->request->data);

            // match
            $match = $this->Bmatch->find('first', array(
                'conditions' => array(
                    'Bmatch.reference_of_transaction' => $this->request->data['Aihexpense']['reference_of_transaction'],  
                ),
            ));
            $match_data = array(
                    'reference_of_transaction' => $this->request->data['Aihexpense']['reference_of_transaction'],
                    'e_name_of_bank' => trim(str_replace('Bank Code:', '', $to_info[0])), 
                    'e_address_of_bank' => trim(str_replace('Bank Code:', '', $to_info[3])), 
                    'bank_code' => $this->request->data['Aihexpense']['bank_code'], 
                    'branch_code' => $this->request->data['Aihexpense']['branch_code'], 
                    'swift_code' => $this->request->data['Aihexpense']['swift_code'], 
                    'e_amount' => $this->request->data['Aihexpense']['amount'], 
                    'e_currency_id' => $this->request->data['Aihexpense']['currency_id'], 
                    'e_currency' => $this->request->data['Aihexpense']['currency'], 
                    'date' => $this->request->data['Aihexpense']['date'], 
                    'status' => 2,
                );
            if(isset($match['Bmatch'])) {
                $match_data['id'] = $match['Bmatch']['id'];
                if($match['Bmatch']['status']===1) {
                    $match_data['status'] = 0;
                } 
                if($match['Bmatch']['amount']==$this->request->data['Aihexpense']['amount']) {
                    $match_data['status'] = 3;
                } else if($match['Bmatch']['amount']!='') {
                    $match_data['status'] = 0;
                }
            }
            
            $this->Aihexpense->create();

            if ($this->Aihexpense->save($this->request->data)) {
                $this->Aihexpense->bmatch($match_data);
                //$this->Session->setFlash(__('The Expense has been saved'), 'default', array('class' => 'success'));
                $contactsids[] = $this->request->data['Aihcontact']['Aihcontact'];
                $this->Aihexpense->lock($contactsids, 'cc_aihcontacts', 1);
                
                if(isset($this->request->data['AccResumeRelated'])){
                    $paymentsid = $this->Paymentschedule->find('first', array('fields' => array('Paymentschedule.id'), 'conditions' => array('refid' => $this->request->data['Aihexpense']['paydetailid'],)));
                    $data = array('id' => $paymentsid['Paymentschedule']['id'], 'expense_status' => 1);
                    $this->Paymentschedule->save($data);
                }
                
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The Expense could not be saved. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
        $accountresumes = $this->Accountresume->find('list', array('fields' => array('Accountresume.refid', 'Accountresume.refid_edit'), 'order' => array('Accountresume.refid_edit ASC'),));
        $this->set(compact('accountresumes'));
        
        $aihcontacts =  $this->Aihcontact->find('list', array('fields' => array('Aihcontact.id', 'Aihcontact.name',),'order' => array('Aihcontact.name ASC'),));

        //$aihpayments = $this->Aihexpense->find('list', array('fields' => array('Aihexpense.paydetailid')));
        //$paymentschedules = $this->Paymentschedule->find('list', array('fields' => array('Paymentschedule.id', 'Paymentschedule.refid'), 'conditions' => array('NOT' => array('Paymentschedule.id' => $aihpayments))));
        $this->set(compact('aihcontacts'));
        
        $currencies =  $this->Currency->find('list', array('fields' => array('Currency.id', 'Currency.name'), 'order' => array('Currency.name ASC')));
        $this->set(compact('currencies'));
    }

    /**
     * Admin edit
     *
     * @param int $id 
     * @return void
     * @access public
     */
    public function admin_edit($id = null) {
        $this->set('title_for_layout', __('AIH EXPENSE DETAIL'));

        $script = $this->datePicker();
        $this->set('script', $script);
        
        $scripts = $this->windowMsg();
        $this->set('windowsscript', $scripts);
        
        $aihcontacts =  $this->Aihcontact->find('list', array('fields' => array('Aihcontact.id', 'Aihcontact.name'),'order' => array('Aihcontact.name ASC'),));
        $this->set(compact('aihcontacts'));

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid ID'), 'default', array('class' => 'error'));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->request->data)) {
            $this->request->data['Aihexpense']['amount'] = $this->request->data['Aihexpense']['amount'];
            $to_info = explode(PHP_EOL, $this->request->data['Aihexpense']['to']);
            $this->request->data['Aihexpense']['bank_code'] = trim(str_replace('Bank Code:', '', $to_info[1]));
            $this->request->data['Aihexpense']['branch_code'] = trim(str_replace('Branch Code:', '', $to_info[2]));
            $this->request->data['Aihexpense']['swift_code'] = trim(str_replace('SWIFT:', '', $to_info[4]));
            $this->request->data['Aihexpense']['date'] = date('Y-m-d', strtotime($this->request->data['Aihexpense']['date']));
            $this->request->data['Aihexpense']['charge_payer'] = $this->request->data['Aihcontact']['Aihcontact'];
            $this->request->data['Aihexpense']['currency_id'] = $this->request->data['Currency']['Currency'];
            $currency = $this->Currency->find('first', array(
                'conditions' => array('Currency.id' => $this->request->data['Currency']['Currency'])));
            $this->request->data['Aihexpense']['currency'] = $currency['Currency']['name'];
            //php_debug($this->request->data);
            //$paymentsid = $this->Paymentschedule->find('first', array('fields' => array('Paymentschedule.id'), 'conditions' => array('refid' => $this->request->data['Aihexpense']['paydetailid'],)));
            //$data = array('id' => $paymentsid['Paymentschedule']['id'], 'expense_status' => 1);
            //$this->Paymentschedule->save($data);
            
            // match
            $conditions = array(
                    'Bmatch.reference_of_transaction' => $this->request->data['Aihexpense']['reference_of_transaction'], 
                );
            $match = $this->Bmatch->find('first', array('conditions' => $conditions));
            $match_data = array(
                    'reference_of_transaction' => $this->request->data['Aihexpense']['reference_of_transaction'],
                    'e_name_of_bank' => trim(str_replace('Bank Code:', '', $to_info[0])), 
                    'e_address_of_bank' => trim(str_replace('Bank Code:', '', $to_info[3])), 
                    'bank_code' => $this->request->data['Aihexpense']['bank_code'], 
                    'bank_code' => $this->request->data['Aihexpense']['bank_code'], 
                    'branch_code' => $this->request->data['Aihexpense']['branch_code'], 
                    'swift_code' => $this->request->data['Aihexpense']['swift_code'], 
                    'e_amount' => $this->request->data['Aihexpense']['amount'], 
                    'e_currency_id' => $this->request->data['Aihexpense']['currency_id'], 
                    'e_currency' => $this->request->data['Aihexpense']['currency'], 
                    'date' => $this->request->data['Aihexpense']['date'], 
                    'status' => 2,
                );
            if(isset($match['Bmatch'])) {
                $match_data['id'] = $match['Bmatch']['id'];
                if($match['Bmatch']['status']===1) {
                    $match_data['status'] = 0;
                } 
                if($match['Bmatch']['amount']==$this->request->data['Aihexpense']['amount']) {
                    $match_data['status'] = 3;
                } else if($match['Bmatch']['amount']!='') {
                    $match_data['status'] = 0;
                }
            }
            
            if ($this->Aihexpense->save($this->request->data)) {
                $this->Aihexpense->bmatch($match_data);
                //$this->Session->setFlash(__('The Expense has been saved'), 'default', array('class' => 'success'));
                $oldcontactsids[] = $this->data['oldContactID'];
                $this->Aihexpense->lock($oldcontactsids, 'cc_aihcontacts', -1);
                $contactsids[] = $this->data['Aihcontact']['Aihcontact'];
                $this->Aihexpense->lock($contactsids, 'cc_aihcontacts', 1);
                        
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The Expense could not be saved. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
        if (empty($this->request->data)) {
            $this->request->data = $this->Aihexpense->read(null, $id);
            $currencies =  $this->Currency->find('list', array('fields' => array('Currency.id', 'Currency.name'), 'order' => array('Currency.name ASC')));
            $this->set(compact('currencies'));
        }
    }

    /**
     * Admin delete
     *
     * @param int $id 
     * @return void
     * @access public
     */
    public function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id'), 'default', array('class' => 'error'));
            $this->redirect(array('action' => 'index'));
        }

        $aihexpense = $this->Aihexpense->find('first', array(
                    'conditions' => array(
                        'id' => $id,
                    ),
                ));
        
        if($aihexpense['Aihexpense']['acc_resume_related'] == 1){
            $paydetailid = $this->Aihexpense->find('first', array(
                'fields' => array('Aihexpense.paydetailid'),
                'conditions' => array(
                    'id' => $id,
                ),
            ));
           
            $paymentsid = $this->Paymentschedule->find('first', array('fields' => array('Paymentschedule.id'), 'conditions' => array('refid' => $paydetailid['Aihexpense']['paydetailid'],)));
            $data = array('id' => $paymentsid['Paymentschedule']['id'], 'expense_status' => 0);
            //php_debug($paymentsid);
            $this->Paymentschedule->save($data);
        }
        
        if (isset($aihexpense['Aihexpense'])) {
            if ($this->Aihexpense->delete($id)) {
                // Reconciliation
                $match = $this->Bmatch->find('first', array('conditions' => array('Bmatch.reference_of_transaction' => $aihexpense['Aihexpense']['reference_of_transaction'])));
                if($match['Bmatch']['amount']=='' && $match['Bmatch']['name_of_bank']=='') {
                    // delete
                    $this->Aihexpense->del_bmatch($match['Bmatch']['id']);
                } else {
                    $data['id'] = $match['Bmatch']['id'];
                    $data['e_amount'] = '';
                    $data['e_name_of_bank'] = '';
                    $this->Aihexpense->bmatch($data);
                }

                $contactsids[] = $aihexpense['Aihexpense']['charge_payer'];
                $this->Aihexpense->lock($contactsids, 'cc_aihcontacts', -1);
            
                //$this->Session->setFlash(__('Expense deleted'), 'default', array('class' => 'success'));
                $this->redirect(array('action' => 'index'));
            }
        } else {
            $this->Session->setFlash(__('Invalid ID '), 'default', array('class' => 'error'));
            $this->redirect(array('action' => 'index'));
        }
    }

    public function admin_getvalue($id = null) {

        $this->layout = 'ajax';
        $success = false;
        if ($id != '') {
            $paymentschedule = $this->Paymentschedule->find('first', array('fields' => array('Paymentschedule.broker_date'), 'conditions' => array('Paymentschedule.refid' => $id)));
            if ($paymentschedule) {
                $success = true;
                $success = $this->Aihexpense->encodeData(array('success' => $success, 'market_date' => date('m/d/Y', strtotime($paymentschedule['Paymentschedule']['broker_date']))), array('json' => true, 'trim' => false));
            }
        } else {
            $success = $this->Aihexpense->encodeData(array('success' => $success));
        }
        $this->set('success', $success);
    }

    public function admin_getpaymentdetail($id = null) {

        $this->layout = 'ajax';
        $success = false;
        if ($id != '') {
            $paymentschedule = $this->Paymentschedule->find('list', array('fields' => array('Paymentschedule.refid', 'Paymentschedule.refid'), 'conditions' => array('Paymentschedule.accountresume_id' => $id, 'Paymentschedule.expense_status' => 0)));
            if ($paymentschedule) {
                $success = true;
                $success = $this->Aihexpense->encodeData(array('success' => $success, 'payments' => $paymentschedule), array('json' => true, 'trim' => false));
            }
        } else {
            $success = $this->Aihexpense->encodeData(array('success' => $success));
        }
        $this->set('success', $success);
    }
    
    public function admin_report($id=null) {
        $this->layout = 'admin_report_resume';
        $this->set('title_for_layout', __('AIH EXPENSE REPORT'));
        
        $aihexpenses = $this->Aihexpense->find('first', array('conditions' => array('Aihexpense.id' => $id,)));
        $charge_name = $this->Aihcontact->find('first', array('fields' => array('Aihcontact.name'), 'conditions' => array('Aihcontact.id' => $aihexpenses['Aihexpense']['charge_payer'],)));
        $aihexpenses['Aihexpense']['charge_name'] = $charge_name['Aihcontact']['name'];
        $this->set('aihexpenses', $aihexpenses);
    }
    
    public function admin_checkreftransunique($id = '') {

        $this->layout = 'ajax';
        $success = false;
        if ($id != '' || $id != 'undefined') {
            $banks = $this->Aihexpense->find('first', array('fields' => array('Aihexpense.reference_of_transaction'), 'conditions' => array('Aihexpense.reference_of_transaction' => $id,)));
            if ($banks) {
                $success = true;
                $success = $this->Aihexpense->encodeData(array('success' => $success, 'isExsist' => '1'), array('json' => true, 'trim' => false));
            }else{
                $success = true;
                $success = $this->Aihexpense->encodeData(array('success' => $success, 'isExsist' => '0'), array('json' => true, 'trim' => false));
            }
        } else {
            $success = $this->Aihexpense->encodeData(array('success' => $success, 'isExsist' => '0'), array('json' => true, 'trim' => false));
        }
        $this->set('success', $success);
    }

    public function datePicker() {
        $output = "
            $(function() {
                $('#AihexpenseDate').datepicker({ changeYear: true });
            });";
        
        return $output;
    }
    public function getJSONdata() {
        $output = "
            $(function() {
                $('#PaymentschedulePaymentschedule').change(function() {
                    $.getJSON('" . Router::url('/admin/aihexpenses/getvalue/', true) . "'+$(this).val(), function(data) {
                        if(data.success) {
                            $('#AihexpenseDate').val(data.market_date);
                        } else {
                            // error
                        }
                    });
                });
                $('#AccountresumeAccountresume').change(function() {
                    $.getJSON('" . Router::url('/admin/aihexpenses/getpaymentdetail/', true) . "'+$('#AccountresumeAccountresume').val(), function(data) {
                        if(data.success) {
                            $('#PaymentschedulePaymentschedule').find('option').remove();
                            for (var key in data.payments) {
                                if (data.payments.hasOwnProperty(key)) {
                                    $('#PaymentschedulePaymentschedule').append('<option value=\"'+key+'\">'+data.payments[key]+'</option>');
                                    
                                }
                            }
                            $.getJSON('" . Router::url('/admin/aihexpenses/getvalue/', true) . "'+$('#PaymentschedulePaymentschedule').first().val(), function(data) {
                                if(data.success) {
                                    $('#AihexpenseDate').val(data.market_date);
                                } else {
                                    // error
                                }
                            });
                        }else{
                            $('#PaymentschedulePaymentschedule').find('option').remove();
                        }
                    });
                });
                
                $('#AihexpenseAdminAddForm').ready(function() {
                    $.getJSON('" . Router::url('/admin/aihexpenses/getpaymentdetail/', true) . "'+$('#AccountresumeAccountresume').val(), function(data) {
                        if(data.success) {
                            $('#PaymentschedulePaymentschedule').find('option').remove();
                            for (var key in data.payments) {
                                if (data.payments.hasOwnProperty(key)) {
                                    $('#PaymentschedulePaymentschedule').append('<option value=\"'+key+'\">'+data.payments[key]+'</option>');
                                    
                                }
                            }
                            $.getJSON('" . Router::url('/admin/aihexpenses/getvalue/', true) . "'+$('#PaymentschedulePaymentschedule').first().val(), function(data) {
                                if(data.success) {
                                    $('#AihexpenseDate').val(data.market_date);
                                } else {
                                    // error
                                }
                            });
                        }else{
                            $('#PaymentschedulePaymentschedule').find('option').remove();
                        }
                    });
                });
                
            });";

        return $output;
    }
    
    public function scriptSearchBox(){
        $output = "
            $(function() {
                $('#search_button').click(function(){
                    if($('#search_text').val() == ''){
                        $(location).attr('href','" . Router::url('/admin/aihexpenses/search/q:', true) . "' + 'all');    
                    }else{
                        $(location).attr('href','" . Router::url('/admin/aihexpenses/search/q:', true) . "' + $('#search_text').val());    
                    }
                });
                $('#search_text').keypress(function(event) {
                    if ( event.which == 13 ) {
                        event.preventDefault();
                        $(location).attr('href','" . Router::url('/admin/aihexpenses/search/q:', true) . "' + $('#search_text').val());
                    }
                });
            });";
        return $output;
    }
    public function windowMsg() {
        $output = "
            $(function() {
                $('a.aihexpense_report').click(function() {
                    childWin = window.open('".Router::url('/admin/aihexpenses/report/', true)."'+$('#AihexpenseId').val(), 'child', 'modal,width=1024,height=768,scrollbars=yes');
                });
            });";
        
        return $output;
    }
}

?>